#include <vector>

struct ListNode
{
    int val;
    ListNode * next;
    ListNode() : val(0), next(nullptr)
    {}
    ListNode(int val) : val(val), next(nullptr)
    {}
    ListNode(int val, ListNode * next) : val(val), next(next)
    {}
};


class Solution 
{
public:
    ListNode* swapPairs(ListNode* head) 
    {
        ListNode * _dummyHead = new ListNode(0);
        _dummyHead->next = head;
        ListNode * cur = _dummyHead->next;
        ListNode * pre = _dummyHead;
        while(cur != nullptr && cur->next != nullptr)
        {
            pre->next = cur->next;
            cur->next = cur->next->next;
            pre->next->next = cur;
            pre = cur;
            cur = cur->next;
        }
        return _dummyHead->next;
    }
};

#include <iostream>

// 辅助函数：根据数组创建链表
ListNode* createList(const std::vector<int>& vals) {
    ListNode* dummy = new ListNode(0);
    ListNode* cur = dummy;
    for (int v : vals) {
        cur->next = new ListNode(v);
        cur = cur->next;
    }
    ListNode* head = dummy->next;
    delete dummy;
    return head;
}

// 辅助函数：打印链表
void printList(ListNode* head) {
    ListNode* cur = head;
    while (cur) {
        std::cout << cur->val;
        if (cur->next) std::cout << "->";
        cur = cur->next;
    }
    std::cout << std::endl;
}

int main() {
    Solution sol;

    // 测试用例1：偶数个节点
    std::vector<int> vals1 = {1, 2, 3, 4};
    ListNode* head1 = createList(vals1);
    std::cout << "原链表1: ";
    printList(head1);
    ListNode* swapped1 = sol.swapPairs(head1);
    std::cout << "交换后1: ";
    printList(swapped1);

    // 测试用例2：奇数个节点
    std::vector<int> vals2 = {1, 2, 3, 4, 5};
    ListNode* head2 = createList(vals2);
    std::cout << "原链表2: ";
    printList(head2);
    ListNode* swapped2 = sol.swapPairs(head2);
    std::cout << "交换后2: ";
    printList(swapped2);

    return 0;
}
